{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "fce2e681",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-05-09T12:08:25.055333Z",
     "start_time": "2022-05-09T12:08:25.046197Z"
    }
   },
   "outputs": [],
   "source": [
    "API_KEY = \"kZNkWCnyruyBYPeYUvX9i2d6\"\n",
    "SECRET_KEY = \"DCfuzoshjzzI4wO6g51dvGcNxFzG3Fm4\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "17203cd4",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-05-09T12:41:18.058983Z",
     "start_time": "2022-05-09T12:41:18.042972Z"
    }
   },
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (Temp/ipykernel_25496/3337262500.py, line 15)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"C:\\Users\\ZHOUXI~1\\AppData\\Local\\Temp/ipykernel_25496/3337262500.py\"\u001b[1;36m, line \u001b[1;32m15\u001b[0m\n\u001b[1;33m    import urllib2 from urllib2\u001b[0m\n\u001b[1;37m                   ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8 \n",
    "import sys\n",
    "import json\n",
    "import time \n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3 \n",
    "\n",
    "if IS_PY3: \n",
    "    from urllib.request import urlopen \n",
    "    from urllib.request import Request \n",
    "    from urllib.error import URLError \n",
    "    from urllib.parse import urlencode \n",
    "    timer = time.perf_counter\n",
    "else: \n",
    "    import urllib2 from urllib2 \n",
    "    import urlopen from urllib2 \n",
    "    import Request from urllib2 \n",
    "    import URLError from urllib \n",
    "    import urlencode \n",
    "    if sys.platform == \"win32\": \n",
    "        timer = time.clock \n",
    "    else: \n",
    "        # On most other platforms the best timer is time.time() \n",
    "        timer = time.time \n",
    "\n",
    "\n",
    "API_KEY = 'kZNkWCnyruyBYPeYUvX9i2d6'\n",
    "SECRET_KEY = 'DCfuzoshjzzI4wO6g51dvGcNxFzG3Fm4' \n",
    "\n",
    "# 需要识别的文件\n",
    "AUDIO_FILE = 'audio/16k.pcm' # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:]; # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式 \n",
    "\n",
    "CUID = '123456PYTHON';\n",
    "# 采样率\n",
    "RATE = 16000;  # 固定值\n",
    "\n",
    "# 普通版\n",
    "\n",
    "DEV_PID = 1537;  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "#测试自训练平台需要打开以下信息， 自训练平台模型上线后，您会看见 第二步：“”获取专属模型参数pid:8001，modelid:1234”，按照这个信息获取 dev_pid=8001，lm_id=1234\n",
    "# DEV_PID = 8001 ;   \n",
    "# LM_ID = 1234 ;\n",
    "\n",
    "# 极速版 打开注释的话请填写自己申请的appkey appSecret ，并在网页中开通极速版（开通后可能会收费）\n",
    "\n",
    "#DEV_PID = 80001\n",
    "#ASR_URL = 'http://vop.baidu.com/pro_api'\n",
    "#SCOPE = 'brain_enhanced_asr'  # 有此scope表示有asr能力，没有请在网页里开通极速版\n",
    "\n",
    "# 忽略scope检查，非常旧的应用可能没有\n",
    "# SCOPE = False\n",
    "\n",
    "\n",
    "# 极速版\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        print(SCOPE)\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    token = fetch_token()\n",
    "\n",
    "    \"\"\"\n",
    "    httpHandler = urllib2.HTTPHandler(debuglevel=1)\n",
    "    opener = urllib2.build_opener(httpHandler)\n",
    "    urllib2.install_opener(opener)\n",
    "    \"\"\"\n",
    "\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "        \n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "    speech = base64.b64encode(speech_data) \n",
    "    if (IS_PY3): \n",
    "        speech = str(speech, 'utf-8') \n",
    "    params = {'dev_pid': DEV_PID,\n",
    "              #\"lm_id\" : LM_ID, #测试自训练平台开启此项 \n",
    "              'format': FORMAT,\n",
    "              'rate': RATE, \n",
    "              'token': token, \n",
    "              'cuid': CUID, \n",
    "              'channel': 1, \n",
    "              'speech': speech, \n",
    "              'len': length } \n",
    "    post_data = json.dumps(params, sort_keys=False)\n",
    "    # print post_data \n",
    "    req = Request(ASR_URL, post_data.encode('utf-8')) \n",
    "    req.add_header('Content-Type', 'application/json')\n",
    "#     异常处理，避免出现红色的bug（提前预判可能出现的异常）\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        print(\"Request time cost %f\" % (timer() - begin))\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')\n",
    "    print(result_str)\n",
    "    with open(\"result.txt\", \"w\") as of: \n",
    "    of.write(result_str)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40b71ab3",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1c98c118",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.4"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
